package com.ldzg.blockwatcher.watcher;

import com.ldzg.blockwatcher.utils.ThreadPoolUtil;
import io.reactivex.functions.Consumer;
import lombok.extern.slf4j.Slf4j;

import java.util.concurrent.atomic.AtomicBoolean;

/**
 * @author 18310740596@163.com
 * @version V1.0.0
 * @since 2025-07-02 10:47:12
 */
@Slf4j
public abstract class AbstractWatcher implements IWatcher {

    private final AtomicBoolean running = new AtomicBoolean(Boolean.FALSE);

    // 默认失败处理,可自行扩展
    protected final Consumer<Throwable> ERROR_FUNC = (ex) -> log.error("监听失败: {}", ex.getMessage(), ex);

    @Override
    public void start() {
        if (!running.get()) {
            // 为了不阻塞主线程执行, 这里采用异步执行, 将监听放入到虚拟线程执行
            ThreadPoolUtil.execute(this::watcher);

            running.set(true);
        }
    }

    @Override
    public void stop() {
        if (running.get()) {
            log.info("监听服务停止");
            running.set(false);

            dispose();
        }
    }

    @Override
    public boolean isRunning() {
        return running.get();
    }
}
